package com.tarena.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;


@Slf4j
public class MyFilter01 implements GlobalFilter, Ordered {
    /**
     * 网关过滤器过滤逻辑执行方法
     * 只要当前过滤器类型在网关生效,所有的请求 都会经过这个方法
     * exchange: 包装了请求和响应等数据的对象
     * chain: 表示当前过滤器所在的过滤链.
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("请求经过了myFilter01");
        //操作请求对象 需要拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //1. 读取path路径 这个path StripPrefix摘取之后的路径还是之前没摘取
        RequestPath path = request.getPath();//cart/hello? /hello
        log.info("请求path路径:{}",path);
        //2.访问全路径地址 url
        URI uri = request.getURI(); //http://127.0.0.1:10000/cart/hello?name=王翠花
        log.info("请求url全地址:{}",uri);
        //3.query参数 请求地址中?key=value格式
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //key是String value List<String> name=王翠花&age=18&age=19
        List<String> names = queryParams.get("name");//list只有一个元素
        List<String> ages = queryParams.get("age");//list有2个元素 一个是18 19
        if (CollectionUtils.isNotEmpty(names)){
            log.info("获取参数names:{}",names);
        }
        if (CollectionUtils.isNotEmpty(ages)){
            log.info("获取参数ages:{}",ages);
        }
        //4. 获取请求的头数据 使用headerName能够拿到headerValue
        HttpHeaders headers = request.getHeaders();
        //获取几个已知的头 Accept Host User-Agent(使用浏览器)
        List<String> accepts = headers.get("Accept");
        log.info("获取请求头Accept:{}",accepts);
        List<MediaType> accept = headers.getAccept();
        log.info("获取请求头Accept:{}",accept);
        //5. Cookie 本质是一个请求头,但是value格式 cookieName1=value1,cookieName2=value2
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> location = cookies.get("location");
        if (CollectionUtils.isNotEmpty(location)){
            log.info("获取请求中的cookie:{}",location);
        }
        //6. 获取请求的远程客户端地址 remoteAddr UNDO
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
